package com.kingstar.ceres.data.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TextFileReader {
    private LineIterator it;
    public TextFileReader(String path) throws IOException {
        LineIterator it = FileUtils.lineIterator(new File(path));
        this.it = it;
    }

    public TextFileReader(String path, String charset) throws IOException {
        LineIterator it = FileUtils.lineIterator(new File(path),charset);
        this.it = it;
    }

    public TextFileReader(File file, String charset) throws IOException {
        LineIterator it = FileUtils.lineIterator(file,charset);
        this.it = it;
    }

    private String readLine(){
        try {
            while (this.it.hasNext()) {
                String line = this.it.nextLine();
                return line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public boolean hasNext(){
        return this.it.hasNext();
    }

    public void close() throws IOException {
        if (this.it!=null){
            this.it.close();
        }
    }

    public List<String> readNextLines(int lines){
        List<String> list=new ArrayList<>(lines);
        for (int i = 0; i < lines; i++) {
            String line = this.readLine();
            if (StringUtils.isNotBlank(line)){
                list.add(line);
            }
        }
        return list;
    }
}